package com.molyfun.parents.activity.msg;

import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.molyfun.parents.MFPApplication;
import com.molyfun.parents.R;
import com.molyfun.parents.activity.msg.adapter.SingleMsgListAdapter;
import com.molyfun.parents.dao.entity.SingleChatDB;
import com.molyfun.parents.dao.gen.DaoMaster;
import com.molyfun.parents.dao.gen.DaoSession;
import com.molyfun.parents.dao.gen.SingleChatDBDao;
import com.molyfun.parents.fragment.BaseFragment;
import com.molyfun.parents.fragment.dialog.CommonDeleteDialogFragment;
import com.molyfun.parents.im.MyTIMMsgListener;
import com.molyfun.parents.im.model.BaseMessageEntity;
import com.molyfun.parents.rest.bean.TeamListResponse;
import com.molyfun.parents.uievent.EventDispatcherEnum;
import com.molyfun.parents.uievent.UIEventListener;
import com.molyfun.parents.utils.Const;
import com.molyfun.parents.utils.PreferencesStorageUtil;
import com.molyfun.parents.view.swipeRefreshLayout.SwipeRefreshLayout;

import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class SingleMsgFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, SwipeRefreshLayout.OnLoadListener, View.OnClickListener,
        SingleMsgListAdapter.SingleMsgClassRoomClickCallback, MyTIMMsgListener.ITIMMsgReceivedCallback, UIEventListener {

    @InjectView(R.id.msg_list)
    RecyclerView mRecyclerView;
    @InjectView(R.id.empty_layout)
    LinearLayout mEmptyLayout;
    @InjectView(R.id.swipe_refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;

    private LinearLayoutManager mLayoutManager;
    private SingleMsgListAdapter mSingleMsgListAdapter;
    private String TAG = "MineMsgActivity";

    //缓存所有小组列表
    HashMap<String, TeamListResponse.TeamBean> conversionNameKv = new HashMap<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_single_msg, container, false);
        ButterKnife.inject(this, view);

        mSwipeRefreshLayout.setOnRefreshListener(this);
        mSwipeRefreshLayout.setOnLoadListener(this);
        mSwipeRefreshLayout.setTopColor(R.color.refresh_color_01, R.color.refresh_color_02,
                R.color.refresh_color_02, R.color.refresh_color_01);
        mSwipeRefreshLayout.setBottomColor(R.color.color_transparent, R.color.color_transparent,
                R.color.color_transparent, R.color.color_transparent);
        mSwipeRefreshLayout.setMode(SwipeRefreshLayout.Mode.BOTH);
        mSwipeRefreshLayout.setLoadNoFull(true);

        mLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mSingleMsgListAdapter = new SingleMsgListAdapter(getContext(), this);
        mRecyclerView.setAdapter(mSingleMsgListAdapter);
        System.out.println(TAG + "onCreateView()");

        MyTIMMsgListener.addITIMMsgReceivedCallback(this);
        MFPApplication.getInstance().getEventController().addUIEventListener(EventDispatcherEnum.UI_EVENT_CHANGE_USERINFO, this);

//        loadData();

        return view;
    }

    @Override
    public void onResume() {
        loadData();
        super.onResume();
    }

    @Override
    public void onMessage(BaseMessageEntity messageEntity) {
        switch (messageEntity.getEventtype()) {
            case MyTIMMsgListener.EventType.IM_MSG:
                if(mSingleMsgListAdapter != null){
                    mSingleMsgListAdapter.addMsgCount(messageEntity.getConversationid());
                }
                loadData();
                break;
        }
    }

    @Override
    public void onRefresh() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
        loadData();
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onLoad() {
        mSwipeRefreshLayout.setRefreshing(false);
        mSwipeRefreshLayout.setLoading(false);
    }


    @Override
    public void onClassRoomLongClick(final SingleChatDB singleChatDB, final int position) {
        if(singleChatDB != null){
            new CommonDeleteDialogFragment.CommonDeleteDialogBuilder("确定删除该对话？")
                    .setCommonDeleteDialogClickListener(new CommonDeleteDialogFragment.CommonDeleteDialogClickListener() {
                        @Override
                        public void onDeleteConfirm() {
                            mSingleMsgListAdapter.remove(position);
                            DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
                            DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());
                            DaoSession daoSession = daoMaster.newSession();
                            SingleChatDBDao mSingleChatDBDao = daoSession.getSingleChatDBDao();

                            if(singleChatDB != null){
                                mSingleChatDBDao.deleteByKey(singleChatDB.getId());
                            }

                        }

                        @Override
                        public void onDeleteCancel() {

                        }
                    })
                    .build(getChildFragmentManager().beginTransaction());

        }
    }

    private void loadData() {
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(MFPApplication.getInstance(), Const.DB_NAME, null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getReadableDatabase());
        DaoSession daoSession = daoMaster.newSession();
        SingleChatDBDao mSingleChatDBDao = daoSession.getSingleChatDBDao();
        if(!TextUtils.isEmpty(PreferencesStorageUtil.getIMUserName(getContext()))){
            List<SingleChatDB> singleChatDBList = mSingleChatDBDao.queryBuilder().where(SingleChatDBDao.Properties.Txuserid.eq(PreferencesStorageUtil.getIMUserName(getContext()))).orderDesc(SingleChatDBDao.Properties.LastMsgTime).list();
            mSingleMsgListAdapter.refreshData(singleChatDBList);
        }else{
            mSingleMsgListAdapter.clearAll();
        }

    }

    @Override
    public void handleUIEvent(Message msg) {

        if (msg.what == EventDispatcherEnum.UI_EVENT_CHANGE_USERINFO) {
            loadData();
        }
    }

//    private void loadDBData(){
//        mSingleMsgListAdapter.refreshData(mSingleChatDBDao.queryBuilder().list());
//    }

}
